import React, { useEffect, useState, forwardRef } from 'react';
import { Button } from 'antd';
import 'codemirror/addon/display/placeholder';
import 'codemirror/addon/scroll/annotatescrollbar';
import 'codemirror/lib/codemirror.css';
import 'codemirror/mode/groovy/groovy';
import 'codemirror/mode/javascript/javascript';
import 'codemirror/mode/xml/xml';
import 'codemirror/theme/material.css';
import { Controlled as CodeMirror } from 'react-codemirror2';
import './script-editor.less';

const ScriptEditor = (props, ref) => {
  const [value, setValue] = useState(props.value || '');
  useEffect(() => {
    setValue(props.value);
  }, [props.value]);
  return (
    <div ref={ref}>
      <CodeMirror
        value={value}
        options={{
          mode: props.mode || 'groovy',
          theme: 'material',
          lineNumbers: true,
          placeholder: props.placeholder,
        }}
        onBeforeChange={(editor, data, value) => {
          if (props.disabled) {
            return;
          }
          setValue(value);
        }}
        onChange={(editor, data, value) => {
          if (props.disabled) {
            return;
          }
          setValue(value);
          props.onChange && props.onChange(value);
        }}
      />
      {props.onSubmit && (
        <div className='submit-area'>
          <Button type='primary' autoFocus={true} onClick={() => props.onSubmit(value)}>
            确定
          </Button>
          <Button onClick={() => props.onCancel && props.onCancel()}>取消</Button>
        </div>
      )}
    </div>
  );
};

export default forwardRef(ScriptEditor);
